<template>
	<div class="m-questionManager m-window">
		<div class="m-help-left" v-if="showType=='list'" v-loading="treeDataLoading">
			<el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
			<el-tree
				class="filter-tree"
				:data="treeData"
				:props="defaultProps"
				default-expand-all
				:filter-node-method="filterNode"
				ref="tree"
				@node-click="treeNodeClick"
			></el-tree>
		</div>
		<div class="m-help-right" v-if="showType=='list'">
			<div class="m-right-header">
				<el-row :gutter="10">
					<el-form :inline-message="true" label-position="left">
						<el-col :span="10">
							<el-form-item label="标题:" label-width="70px" class="rightItem">
								<el-input placeholder="输入标题" v-model="questionTitle"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="2" :offset="2">
							<el-button type="primary" @click="search(1)">查询</el-button>
						</el-col>
						<el-col :span="2">
							<el-button type="primary" @click="viewDetail">查看</el-button>
						</el-col>
						<el-col :span="2">
							<el-button type="primary" @click="addNewQuestion">新增</el-button>
						</el-col>
						<el-col :span="2">
							<el-button type="primary" @click="editQuestion" :disabled="!btnDisabled">编辑</el-button>
						</el-col>
						<el-col :span="2">
							<el-button type="primary" @click="deletedData(-1)">删除</el-button>
						</el-col>
						<el-col :span="2">
							<el-button type="primary" @click="deletedData(0)" :disabled="btnDisabled">撤销</el-button>
						</el-col>
					</el-form>
				</el-row>
			</div>
			<div class="m-right-content" v-loading="loading">
				<div class="m-agTable">
					<agGridComponents
						ref="agGridComponent"
						:getColumnDefs="columnDefs"
						:getRowSelection="'multiple'"
						:getGridOptions="gridOptions"
						:getRowData="rowData"
						:isColFit="true"
					></agGridComponents>
				</div>
			</div>
			<div class="m-page">
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageInfo.current"
					:page-sizes="[30,50,100,150,200]"
					:page-size="pageInfo.size"
					layout="total, sizes, prev, pager, next, jumper"
					:total="pageInfo.total"
				></el-pagination>
			</div>
		</div>
		<!-- 编辑问题 -->
		<question-edit
			v-if="dialogVisible"
			@cancelEdit="goBackList"
			:dialogTitle="dialogTitle"
			:dialogVisible="dialogVisible"
			:ruleForm="ruleForm"
			:parentOptions="treeData"
			:files="files"
		></question-edit>
		<!-- 问题详情 -->
		<question-view @goBackList="goBackList" v-if="showType=='view'" :detail="ruleForm"></question-view>
	</div>
</template>

<script>
import QuestionEdit from "./common/questionEdit"
import QuestionView from "./common/questionView"
import Msg from "@/public/message"
import gridOptions from 'lesso-common/public/gridOptions';
import agGridComponents from "@/components/agGridComponents"
export default {
	data () {
		return {
			// 页面显示内容
			showType: 'list',
			//  树过滤值
			filterText: '',
			//   问题标题查询
			questionTitle: '',
			//   树数据
			treeData: [],
			treeDataLoading: false,
			//   树属性配置
			defaultProps: {
				children: 'childs',
				label: 'enumName'
			},
			//   分页相关
			pageInfo: {
				size: 30,
				current: 1,
				total: 0
			},
			//   列配置
			columnDefs: [],
			//   表格配置
			gridOptions: {},
			rowData: [],
			//   表格 数据加载
			loading: false,
			//   新增/编辑弹窗显示
			dialogVisible: false,
			//   弹窗标题
			dialogTitle: '',
			// 分类编码
			enumTypes: [],
			questionInfo: {},
			//   新增或编辑表单信息
			ruleForm: {
				title: '',
				priority: 0,
				content: '',
				type: '',
				traType: 2
			},
			//   按钮不可操作状态
			btnDisabled: false,
			//   问题分类集合
			parentOptions: [],
			//   回显文件信息
			files: []
		}
	},
	props: {
		addTab: {
			type: Function
		}
	},
	methods: {
		//   过滤树节点
		filterNode (value, data) {
			if (!value) return true;
			return data.enumName.indexOf(value) !== -1;
		},
		// 查询问题列表数据
		search (flag) {
			if (flag) this.pageInfo.current = 1
			const { current, size } = this.pageInfo
			let params = {
				likeParams: {
					title: this.questionTitle//问题标题
				},
				eqParams: {
				},
				inParams: {
					type: this.enumTypes
				},
				current,
				size
			}
			this.loading = true
			this.$http.getQuestionList(params).then(({ data }) => {
				this.loading = false
				if (data.code == 1) {
					let rowData = data.rows
					this.$refs['agGridComponent'].gridOptions.api.setRowData(rowData)
					this.pageInfo.total = data.total
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 每页显示条数改变
		handleSizeChange (val) {
			this.pageInfo.size = val
			this.search(1)
		},
		// 页码改变
		handleCurrentChange (val) {
			this.pageInfo.current = val
			this.search()
		},
		// 点击树节点回调
		treeNodeClick (treeItem, node) {
			this.enumTypes = []
			foreachChilds(treeItem, this.enumTypes)
			function foreachChilds (arr, typeCodes) {
				const { childs } = arr
				if (Array.isArray(childs) && childs.length > 0) {
					childs.forEach(item => {
						typeCodes.push(item.enumCode)
						foreachChilds(item, typeCodes)
					})
				}
			}
			this.enumTypes.push(treeItem.enumCode)
			this.search(1)
		},
		// 获取问题类型树
		getTreeData () {
			this.treeDataLoading = true
			this.$http.getQuestionTypeTree({ enumCode: 'questionType' }).then(({ data }) => {
				this.treeDataLoading = false
				if (data.code == 1) {
					this.treeData = data.rows
					this.parentOptions = data.rows
					setCodes(this.parentOptions)
					// 递归设置节点属性
					function setCodes (arr) {
						arr.forEach(item => {
							if (item.state == 1) {
								item.disabled = true
							} else {
								item.disabled = false
							}
							if (Array.isArray(item.childs)) {
								if (item.childs.length > 0) {
									setCodes(item.childs)
								} else {
									item.childs = null
								}
							} else {
								item.childs = null
							}
						})
					}
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.treeDataLoading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 新增问题
		addNewQuestion () {
			this.ruleForm = {
				title: '',
				priority: 0,
				content: '',
				type: '',
				traType: 2,
				state: 0,
				attachments: []
			}
			this.files = []
			this.dialogTitle = "问题新增"
			this.dialogVisible = true
		},
		// 编辑问题
		editQuestion () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			if (row.length <= 0) {
				this.$alert("提示：请选择需要编辑的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			} else if (row.length > 1) {
				this.$alert("提示：每次只能编辑一条数据！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			this.files = []
			const { title, state, content, priority, type, traType, id, attachments } = row[0]
			attachments.forEach(item => {
				let file = {}
				file.url = item.url
				file.size = item.size
				file.group = 'SRM'
				file.name = item.name
				file.md5 = item.md5 || '123'
				file.ID = item.ID
				file.iconShow = false
				this.files.push(file)
			})
			this.ruleForm = {
				title,
				state,
				content,
				priority,
				type,
				traType,
				id,
				attachments
			}
			this.dialogTitle = "问题编辑"
			this.dialogVisible = true
		},
		// 查看问题详情
		viewDetail () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			if (row.length <= 0) {
				this.$alert("提示：请选择需要查看的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			} else if (row.length > 1) {
				this.$alert("提示：每次只能查看一条数据！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			const { title, content, attachments } = row[0]
			this.ruleForm = {
				title,
				content,
				attachments
			}
			this.showType = 'view'
		},
		// 删除or撤销数据
		deletedData (state) {
			// state-1删除，state为0撤销
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			let msg = state == -1 ? '删除' : '撤销'
			if (row.length <= 0) {
				this.$alert(`提示：请选择需要${msg}的数据`, {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			let isPublished = row.some(item => {
				return item.state == 1
			})
			let alertMsg = ''
			if (state == -1) {
				if (isPublished) {
					alertMsg = '存在已发布的问题，是否确认删除,删除后数据将不可恢复?'
				} else {
					alertMsg = '是否确认删除,删除后数据将不可恢复?'
				}
			} else {
				alertMsg = '是否撤销已选择问题?'
			}
			this.$confirm(alertMsg, "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(_ => {
				let params = {
					ids: [],
					state: state,
					modifyer: this.$global.user.employeeName,
					modifyerId: this.$global.user.id
				}
				params.ids = row.map(item => {
					return item.id
				})
				this.$http.deletedQuestion(params).then(({ data }) => {
					if (data.code == 1) {
						Msg.showSuccessMsg(`数据已${msg}`)
						this.search(1)
					} else {
						Msg.showErrorMsg(data.info)
					}
				}).catch(err => {
					Msg.showErrorMsg(err.data.message)
				})
			}).catch(_ => { })
		},
		goBackList (val) {
			this.dialogVisible = false
			this.showType = 'list'
			if (val == 'add') {
				this.enumTypes = []
				this.search(1)
			} else {
				this.search(1)
			}
		}
	},
	watch: {
		filterText (val) {
			this.$refs.tree.filter(val);
		}
	},
	components: {
		QuestionEdit,
        QuestionView,
        agGridComponents
	},
	beforeMount () {
		this.gridOptions = Object.assign({
			context: {
				componentParent: this
			},
			onRowSelected: (gird) => {
				let rows = gird.api.getSelectedRows()
				this.btnDisabled = rows.some(item => {
					return item.state == 0
				})
			},
		}, gridOptions({ dragSelectCheckbox: true, singleSelection: true, operation: true }))
		this.columnDefs = [
			{ headerName: "", field: "", width: 60, checkboxSelection: true, headerCheckboxSelection: true },
			{
				headerName: "序号",
				field: "",
				width: 70,
				cellRenderer: (params) => {
					return params.rowIndex + 1
				}
			},
			{ headerName: "标题", field: "title", width: 140, tooltipField: 'title' },
			{ headerName: "创建人", field: "creator", width: 100 },
			{
				headerName: "创建日期",
				field: "createDate",
				width: 120,
				cellRenderer: (params) => {
					if (params.value)
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "发布人", field: "releaser", width: 100 },
			{
				headerName: "发布日期",
				field: "releaseDate",
				width: 120,
				cellRenderer: (params) => {
					if (params.value)
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "上级分类", field: "enumName", width: 100 },
			{
				headerName: "问题类别",
				field: "priority",
				width: 140,
				cellRenderer: (params) => {
					if (params.value == 0)
						return '<span class="ag-icon">普通</span>'
					else if (params.value == 1)
						return '<span class="ag-icon">常见</span>'
				}
			},
			{
				headerName: "查看对象类型",
				field: "traType",
				width: 140,
				cellRenderer: (params) => {
					if (params.value == 0)
						return '<span class="ag-icon">供应商</span>'
					else if (params.value == 1)
						return '<span class="ag-icon">内部用户</span>'
					else if (params.value == 2)
						return '<span class="ag-icon">全部</span>'
				}
			},
			{
				headerName: "状态",
				width: 100,
				field: "state",
				cellRenderer: function (params) {
					if (params.value == 0)
						return '<span class="ag-icon">未发布</span>'
					else if (params.value == 1)
						return '<span class="ag-icon">已发布</span>'
				}
			}];
	},
	mounted () {
		this.getTreeData()
		this.search(1)
	}
}
</script>
<style lang="less" scoped>
.m-questionManager {
	display: flex;
	.m-help-left {
		min-width: 300px;
		max-width: 500px;
		padding: 10px;
		border: 1px solid #dcdfe6;
		.el-tree {
			margin-top: 10px;
		}
	}
	.m-help-right {
		flex: 1;
		position: relative;
		.el-row {
			.el-form {
				.el-form-item {
					margin-bottom: 10px;
				}
			}
			.el-col-2 {
				min-width: 60px;
			}
		}
		.m-right-content {
			position: absolute;
			left: 22px;
			right: 0;
			bottom: 30px;
			top: 50px;
			overflow: auto;
			.m-agTable {
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				bottom: 5px;
			}
		}
	}
}
</style>